/// <reference path="routing/Route.js" />
/// <reference path="routing/RouteRepository.js" />
/// <reference path="utilities/Xpcom.js" />
///--------------------------------------------------------------------
/// <file name="Init.js">
///   Where everything starts. Hooks up to the DOMContentLoaded event
///   of the window and starts the process of adding functionality
///   to a page based on the URL.
/// </file>
///--------------------------------------------------------------------

NAMFox.ns(function() { with (NAMFox) {

    var routeRepository = new RouteRepository();

    var root = "^www.neoseeker.com";
    var blogRoot = "^blogs.neoseeker.com/";

    var memberRoot = root + "/members/";
    var forumRoot = root + "/forums/";


    //////////////////////////////////////
    // Profile Routes                   //
    //////////////////////////////////////
    routeRepository.addRoute(
        new Route(
            memberRoot + "modcp.html$",
            new ModeratorControlPanelHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            memberRoot + "edit_profile.html(?:\\?edit=forum_settings)?$",
            new ForumSettingsHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            memberRoot + "edit_profile.html\\?.*$",
            new NewCustomSmileyHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            memberRoot + "(?<member>.*?)/guestbook/\\?function=sign$",
            new SignGuestbookHandler()
        )
    );

    //////////////////////////////////////
    // Forum Routes                     //
    //////////////////////////////////////
    routeRepository.addRoute(
        new Route(
            forumRoot + "index.php\\?.*?fn=moderation_queue.*$",
            new ModerationQueueHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            forumRoot + "index.php\\?.*?fn=(?:delete_message|mass_message_change).*$",
            new DeleteMessageHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            forumRoot + "(?<forumId>.*?)/t(?<threadId>.*?)-.*$",
            new ViewThreadHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            forumRoot + "(?<forumId>[^/]*?)/((?:\\d+\\.htm)?|\\?.*?)$",
            new ViewForumHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            forumRoot + "index.php\\?.*?fn=add_member_ban.*?$",
            new BanMemberHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            forumRoot + "index.php(?:\\?.*?fn=(?:open|close|move)_thread.*?)?$",
            new AdministerThreadHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            forumRoot + "index.php(?:\\?.*?fn=(?:post_(?:reply|thread)|edit_message).*?)?$",
            new PostHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            forumRoot + "(?:index.php\\?.*?fn=(?:send|view)_pm_thread.*?)?$",
            new PrivateMessageHandler()
        )
    );


    //////////////////////////////////////
    // Blog Routes                      //
    //////////////////////////////////////
    routeRepository.addRoute(
        new Route(
            blogRoot + "(?:\\?page=(?<page>\\d+))?$",
            new ViewAllBlogsHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            blogRoot + "(?<author>[^\\?/]+?)(?:/(?:\\?page=(?<page>\\d+))?)?$",
            new ViewBlogHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            blogRoot + "post.php",
            new CreateBlogPostHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            blogRoot + "(?<author>[^\\?/]+?)/(?<postId>.+?)-.*$",
            new ViewBlogPostHandler()
        )
    );


    //////////////////////////////////////
    // Catch All                        //
    //////////////////////////////////////
    function FooHandler() {
    }

    FooHandler.prototype = new RequestHandler();
    FooHandler.prototype.handleRequestCore = function(request, _$) {
        function markupReceived(markup) {
            alert("MARKUP RECEIVED: " + markup);
        }

        _$("#foo").click(function() {
            MarkupTranslator.getMarkupFromHtml(request.htmlDocument, "!Header 1\nLorem ip[sup][u]sum[/u][/sup]\n!!Header 2\n[b]Lorem[/b] ipsum\n!!!Header 3\nLorem [i]ipsum[/i]\n!!!!Header 4\nL[strike]or[/strike]em [[#headers|ipsum]]\n!!!!!Header 5\n[[member:Lorem ipsum]] @NAMFox Test Account@\n# Some list\n# of [b]items[/b]\n## ne[link name=sted list]http://www.bing.com/[/link]\n** of items\n* [[pm:Artificer|with]] bullets\n** and [[member:Torah|more]] bullets\n*** and even more\n### but [[pm:back to]] numbers\n[li]Fooled you with an old bullet\n[li]and another\n[ol]\n[li]And the old numbers\n[ul]\nindented\n[li]And bullets\n[/ul]\n[/ol]\n\n[[#headers]]\n=Wiki Header 1=\n[color=green]Lorem[/color] [http://www.google.com ipsum]\n==Wiki Header 2==\nLorem [color=#ABCDEF]ipsum[/color] @Artificer\n===Wiki Header 3===\n[[pm:Lorem ipsum|subject:Hello]]\n====Wiki Header 4====\n[[pm:Lorem ipsum|subject:Lorem ipsum|Lorem ipsum 2 u]]\n=====Wiki Header 5=====\n[div align=left]Lor[/div][div align=center]em[/div] [div align=right]i[i]psu[/i]m[/div]\n\n[float=left]\n[code]\nfunction inception() {\n    return inception();\n}\n[/code]\n[/float]\n\n[float=right]\n[php]\nfunction getMovie() {\n    return this.airbenders[this.airbenders.length - 1];\n}\n[/php]\n[/float]\n\n[pre]Sometimes i wonder\nwhy there are so many tags\ncomplicated sigh[/pre]\n[hr]\n[spoiler=Videos][youtube]vwIEqNWykzM[/youtube][gamespot]6187403[/gamespot][gametrailers]25549[/gametrailers][gametrailers_uservideo]114364[/gametrailers_uservideo][gamevideos]13971[/gamevideos][ignvideo]object_ID=826967&downloadURL=http://ps3movies.ign.com/ps3/video/article/824/824567/folklore_vidreview_100207_flvlowwide.flv[/ignvideo][neovid]Mzc0LU5BTUZveCBBdXRvQ29tcGxldGU=[/neovid][neovid size=480]Mzc0LU5BTUZveCBBdXRvQ29tcGxldGU=[/neovid][yt]vwIEqNWykzM[/yt][yt]http://www.youtube.com/watch?v=vwIEqNWykzM[/yt][/spoiler]\n[hr]\n[img link=http://www.neoseeker.com/]http://i.neoseeker.com/f/neo/community_online.gif[/img]\n[img]http://i.neoseeker.com/f/neo/profile_ico_red.gif[/img]\n[link]https://addons.mozilla.com/[/link]\n[hr]\n[q=Artificer 2]Hi[/q]\n[q=NAMFox Test Account|http://www.bing.com]Important informations[/q]\n[q=Art|message:12345678]failure[/q]\n[q][size=1]h[/size][size=2]a[/size][size=3]h[/size][size=4]a[/size][/q]\n\n[spoiler=I've got a secret]I win:angry::thick::colored:^_^:o:#:cool::confused::D;(:|:(;):P:):ashamed::hypno::_puke::sonic::sonicshadow:o_O:laugh::angelwings::_devil2::angel::blackeye::_dead::_devil::eating::_phantom::rainbow::sleeping::annoyed:o.O�_�:_dumbfounded::blinkyeyes::rolleyes::moony::_oooh::shifty::_oops::notamused::whatever::suikiasmile::coolcat::lock::redanger::frag::skully8::_ps_tri::_ps_circle::_ps_x::_ps_[]::_ps_up::_ps_right::_ps_down::_ps_left::_ps_l1::_ps_l2::_ps_r1::_ps_r2::epic::bigfrown::nothappy::ninja::XD;:_pointy1::_pointy2::shocked::salty::happy:<3;</3;:yoshi:[faqimg=389]http://i.neoseeker.com/m/31026_photo.gif[/faqimg]:_pokeball::kirby::1up::shroom::yinyang::triforce::mario::luigi::samus::snake::meteormateria::holymateria:[/spoiler]", markupReceived);
        });
    };

    routeRepository.addRoute(
        new Route(
            root + ".*$",
            new CatchAllHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            blogRoot + ".*$",
            new CatchAllHandler()
        )
    );
    routeRepository.addRoute(
        new Route(
            ".*$",
            new FooHandler()
        )
    );

    

    this.onDOMContentLoaded = function(event) {
        /// <summary>
        /// Runs every time an HTML Document loads and ensures this is a Neoseeker URL
        /// before handing off the request to the routing handler.
        /// </summary>

        try {
            var htmlDocument = event.originalTarget;

            // Don't load frames.
            if (htmlDocument.defaultView.frameElement) {
                return;
            }

            try {
                var url = htmlDocument.location.href;
                var domain = htmlDocument.domain;
            }
            catch (e) {
                // If the htmlDocument has been disposed, then these property
                // calls will throw.
                return;
            }

            if (/^(?:chrome|about|http:\/\/i\.neoseeker\.com)/.test(url)) {
                // Calling the doc.domain property on chrome:// urls breaks Firefox.
                return;
            }

            // if (domain && domain.match(/neoseeker.com/)) {
                // For storing arbitrary data that is document-specific.
                htmlDocument.__namfox__ = {};
                routeRepository.handleRequest(htmlDocument);
            // }
        }
        catch (e) {
            $.error(e);
        }
    };

    this.showUpdates = function() {
        /// <summary>
        ///   Assesses whether we need to show updates for a new installation.
        /// </summary>

        try {
            var namfoxVersion = "1.7.2";
            var updates = $.getConfig().shownUpdates;
            if (!updates || updates !== namfoxVersion) {
                var newUserUrl = $.url.forum("/115/t1162186-namfox-faq-1/");
                var updateUrl = "http://www.neoseeker.com/forums/directmessage.php?m=31515854";

                // If we're in an intermediate build (e.g. "pre"), then updateUrl will be empty.
                if (updates && !updateUrl) {
                    return;
                }

                // I don't understand what the difference is that requires
                // this code in NAMFox 1.1+ and something much simpler in
                // NAMFox 1.0.5. Essentially, it doesn't seem as though the
                // gBrowser actually loads the correct URL. (Maybe it is too
                // early for it to be called?) However, once the tab loads
                // the first time, it usually points to about:blank. We hijack
                // that to point to the real updateUrl.
                var tab = gBrowser.selectedTab = gBrowser.addTab(updateUrl);
                var browser = gBrowser.getBrowserForTab(tab);

                var handler = function(event) {
                    var htmlDocument = event.originalTarget;

                    // Don't load frames.
                    if (htmlDocument.defaultView.frameElement) {
                        return;
                    }

                    browser.removeEventListener("load", handler, true);

                    updates = $.getConfig().shownUpdates;
                    if (!updates) {
                        if (htmlDocument.location.href !== newUserUrl) {
                            // By this time the gBrowser is actually responsive.
                            gBrowser.selectedTab = gBrowser.addTab(newUserUrl);
                        }
                        else {
                            gBrowser.selectedTab = tab;
                        }
                    }
                    else if (updates !== namfoxVersion) {
                        if (htmlDocument.location.href !== updateUrl) {
                            // By this time the gBrowser is actually responsive.
                            gBrowser.selectedTab = gBrowser.addTab(updateUrl);
                        }
                        else {
                            gBrowser.selectedTab = tab;
                        }
                    }

                    $.getConfig().shownUpdates = namfoxVersion;
                };

                browser.addEventListener(
                    "load",
                    handler,
                    true
                );
            }
        }
        catch (e) {
            $.error(e);
        }
    };
    
    $.getConfig().update();
    $.refreshCurrentUser();
    this.showUpdates();

    window.addEventListener("DOMContentLoaded", this.onDOMContentLoaded, false);
}});
